package study.thread.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
 * 使用JDK提供的线程池有以下几步：
 * 1.创建线程目标对象，可以是不同的；
 * 2.使用Executors创建线程池，返回ExecutorService对象；
 * 3.使用线程池执行线程目标对象；
 * 4.最后关闭线程池中的线程。
 */
public class TestThreadPool {
	
	public static void main(String[] args) {
		//在线程池中创建两个线程
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		
		//创建100个线程目标对象
		for (int i = 0; i < 100; i++) {
			Runnable run = new MyRunnable(i);
			
			//执行线程目标对象
			executorService.execute(run);
		}
		
		//关闭
		executorService.shutdown();
	}
	

}

class MyRunnable implements Runnable {
	
	private int index = 0;
	
	public MyRunnable(int index) {
		this.index = index;
	}
	
	public void run() {
		long time = (long) (Math.random()*1000);
		
		System.out.println("线程："+Thread.currentThread().getName()+" (目标对象"+index+")"+" 睡眠了"+time+"ms");
		
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
